package logic

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
	"log"
	"vip_video/configx"
	"vip_video/internal/library"
	"vip_video/models"
)

type VideoLogic struct {
	db     *sqlx.DB
	config *configx.Config
	_ctx   *gin.Context
}

func NewVideoLogic(db *sqlx.DB) *VideoLogic {
	return &VideoLogic{
		db: db,
	}
}

func (vl *VideoLogic) WithConfig(config *configx.Config) *VideoLogic {
	vl.config = config
	return vl
}

func (vl *VideoLogic) M3u8(chapterId int64) (string, error) {
	var videoChapter models.VideoChapterModel
	if err := vl.db.Get(&videoChapter, "select * from fa_video_chapter where id=?", chapterId); err != nil {
		return "", errors.New("获取章节失败")
	}
	//查询渠道
	var videoChannel models.VideoChannelModel
	if err := vl.db.Get(&videoChannel, "select * from fa_video_channel where id = ?;", videoChapter.ChannelId); err != nil {
		return "", errors.New("获取渠道失败")
	}
	url, err := library.NewParseVideo().
		WithType(videoChannel.Type).
		WithHandleName(videoChannel.Handle).
		WithConfig(vl.config).
		Parse(videoChapter.Url)
	if err != nil {
		return "", errors.New(err.Error())
	}
	//增加观看次数
	_, err = vl.db.Exec("update fa_video set view_num = view_num + 1 where id = ?", videoChannel.VideoId)
	if err != nil {
		log.Printf("增加观看次数失败:%s", err.Error())
	}
	return url, nil
}

func (vl *VideoLogic) Record(auth *library.AuthLibrary, chapterId int64, second int64) error {
	//查询文章是否存在

	var chapterModel models.VideoChapterModel
	if err := vl.db.Get(&chapterModel, "select * from fa_video_chapter where id = ?;", chapterId); err != nil {
		return errors.New("文章不存在")
	}
	_, err := vl.db.NamedExec(
		"insert into fa_chapter_history(chapter_id,user_id,second,creator) values(:chapter_id,:user_id,:second,:creator) on duplicate key update second = values(second);",
		map[string]any{
			"chapter_id": chapterId,
			"user_id":    auth.GetUserId(),
			"second":     second,
			"creator":    auth.GetUserNickName(),
		},
	)
	if err != nil {
		log.Printf("记录观看历史失败:%s", err.Error())
		return errors.New("系统错误")
	}
	return nil
}
